﻿/*
Copyright (c) 2009 Vratislav Cermak (vratacermak@gmail.com)
 
This file is part of TeachMe Project. See http://code.google.com/p/teach-me for more information.
 
TeachMe is an open source project. Using of TeachMe is free of charge.
It is distributed under GNU General Public License version 3 (GPLv3).
GPLv3 can be found at http://www.gnu.org/licenses/gpl.html.
 
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

using System;
using System.Collections.Generic;
using System.Drawing;

namespace TeachMe.Application.Drawing
{
    public class TextDrawingContext
    {
        public Rectangle Rectangle { get; set; }
        public Brush Brush { get; set; }
        public Brush HighlightBrush { get; set; }
        public Font Font { get; set; }
        public string Text { get; set; }
        public string HighlightText { get; set; }

        public void Draw(Graphics graphics, bool highlight)
        {
            if (String.IsNullOrEmpty(HighlightText) || !highlight)
            {
                graphics.DrawString(Text, Font, Brush, Rectangle);
                
                return;
            }

            var idx = 0;
            var ranges = new List<CharacterRange>();
            var highlightTextLen = HighlightText.Length;
            string lowText = Text.ToLower(), lowHighlightText = HighlightText.ToLower();

            while (idx < lowText.Length)
            {
                var sub = lowText.Substring(idx);

                if (!sub.Contains(lowHighlightText))
                {
                    break;
                }

                ranges.Add(new CharacterRange(sub.IndexOf(lowHighlightText) + idx, highlightTextLen));

                idx += sub.IndexOf(lowHighlightText) + highlightTextLen;
            }

            var stringFormat = new StringFormat();

            stringFormat.SetMeasurableCharacterRanges(ranges.ToArray());

            var charRegion = graphics.MeasureCharacterRanges(Text, Font, Rectangle, stringFormat);

            foreach (var characterRange in charRegion)
            {
                graphics.FillRegion(HighlightBrush, characterRange);
            }

            graphics.DrawString(Text, Font, Brush, Rectangle);
        }
    }
}
